<template>
  <div class="orders-container">
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
            <el-option label="待服务" value="accepted" />
            <el-option label="服务中" value="inProgress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="order-list">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部订单" name="all" />
        <el-tab-pane label="待服务" name="accepted" />
        <el-tab-pane label="服务中" name="inProgress" />
        <el-tab-pane label="已完成" name="completed" />
      </el-tabs>

      <div class="order-items">
        <el-card
          v-for="order in orderList"
          :key="order.id"
          class="order-item"
        >
          <template #header>
            <div class="order-header">
              <div class="left">
                <span class="order-no">订单号：{{ order.id }}</span>
                <el-tag :type="getStatusType(order.status)">
                  {{ getStatusText(order.status) }}
                </el-tag>
              </div>
              <div class="right">
                <span class="time">{{ order.starttime }}</span>
              </div>
            </div>
          </template>

          <div class="order-content">
            <div class="patient-info">
              <h4>患者信息</h4>
              <p>姓名：{{ order.name }}</p>
              <p>性别：{{ order.gender === 'male' ? '男' : '女' }}</p>
              <p>年龄：{{ order.age }}岁</p>
              <p>联系电话：{{ order.phone }}</p>
              <p>医院：{{ order.hospital }}</p>
              <p>科室：{{ order.department }}</p>
            </div>

            <div class="service-info">
              <h4>服务信息</h4>
              <p>服务时间：{{ order.time }}小时</p>
              <p>备注：无</p>
            </div>

          </div>

          <div class="order-footer">
            <template v-if="order.status === 'accepted'">
              <el-button type="primary" @click="handleStartService(order)">开始服务</el-button>
              <el-button type="danger" @click="handleCancel(order)">取消订单</el-button>
            </template>
            <template v-else-if="order.status === 'inProgress'">
              <el-button type="success" @click="handleComplete(order)">完成服务</el-button>
              <el-button type="primary" @click="handleAddRecord(order)">添加记录</el-button>
            </template>
            <template v-else-if="order.status === 'completed'">
              <el-button type="primary" link @click="viewServiceRecord(order)">查看服务记录</el-button>
            </template>
          </div>
        </el-card>

        <el-empty v-if="!orderList.length" description="暂无订单" />
      </div>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加服务记录对话框 -->
    <el-dialog
      v-model="recordDialogVisible"
      title="添加服务记录"
      width="600px"
    >
      <el-form :model="recordForm" :rules="recordRules" ref="recordFormRef" label-width="100px">
        <el-form-item label="服务内容" prop="content">
          <el-input
            v-model="recordForm.content"
            type="textarea"
            rows="4"
            placeholder="请详细描述服务过程..."
          />
        </el-form-item>
        <el-form-item label="图片记录">
          <el-upload
            action="/api/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="位置信息">
          <el-button @click="getLocation">
            <el-icon><Location /></el-icon>
            获取当前位置
          </el-button>
          <span v-if="recordForm.location" class="location-text">
            {{ recordForm.location }}
          </span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="recordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRecord">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog v-model="previewVisible">
      <img w-full :src="previewUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import {ip} from '@/router/ip.js'

// 订单列表数据
const orderList = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选表单数据
const filterForm = reactive({
  status: '',
  dateRange: []
})

// 活动标签
const activeTab = ref('all')


// Orders.vue 的 fetchOrders 函数修改
// Orders.vue 的 fetchOrders 函数修改
const fetchOrders = async () => {
    const caregiverId = localStorage.getItem('caregiverId');
    console.log('从 localStorage 中获取的陪诊师ID:', caregiverId);
    if (!caregiverId) {
      ElMessage.error('未获取到陪护师信息');
      return;
    }

    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: filterForm.status,
      startDate: filterForm.dateRange?.[0],
      endDate: filterForm.dateRange?.[1],
      caregiverId
    };

    console.log('即将发送的请求参数:', params);

    const response = await axios.get(`http://${ip}:8000/api/getMyOrders`, { params });

    console.log('请求响应状态:', response.status);
    console.log('请求响应数据:', response.data);

    if (Array.isArray(response.data)) {
      orderList.value = response.data.map(order => ({
        id: order.id,
        status: order.status,
        starttime: new Date(order.starttime).toLocaleString(),
        name: order.name,
        gender: order.gender,
        age: order.age,
        phone: order.phone,
        hospital: order.hospital,
        department: order.department,
        time: (order.time / 3600).toFixed(0)
      }));
      total.value = response.data.length; // 假设返回的数组长度就是总数量
    } else {
      console.error('返回的数据格式错误:', response.data);
      ElMessage.error('获取订单数据格式错误');
    }
};

// 修改订单状态操作
const updateOrderStatus = async (orderId, newStatus) => {
  try {
    await axios.post(`http://${ip}:8000/api/updateOrderStatus`, {
      id: orderId,
      status: newStatus
    })
    await fetchOrders()
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 开始服务
const handleStartService = async (order) => {
  try {
    await ElMessageBox.confirm('确认开始服务？', '提示')
    await updateOrderStatus(order.id, 'inProgress')
  } catch {}
}

// 完成服务
const handleComplete = async (order) => {
  try {
    await ElMessageBox.confirm('确认完成服务？', '提示')
    await updateOrderStatus(order.id, 'completed')
  } catch {}
}

// 取消订单
const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm('确认取消订单？', '提示')
    await updateOrderStatus(order.id, 'cancelled')
  } catch {}
}

// 查询按钮点击事件
const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

// 重置按钮点击事件
const resetFilter = () => {
  filterForm.status = ''
  filterForm.dateRange = []
  currentPage.value = 1
  fetchOrders()
}

// 标签点击事件
const handleTabClick = (tab) => {
  filterForm.status = tab.name === 'all' ? '' : tab.name
  currentPage.value = 1
  fetchOrders()
}

// 每页数量改变事件
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchOrders()
}

// 当前页码改变事件
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchOrders()
}

// 获取订单状态标签类型
const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    confirmed: 'success',
    completed: 'info',
    cancelled: 'danger',
    accepted: 'primary',
    inProgress: 'success'
  }
  return types[status] || 'info'
}

// 获取订单状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '待支付',
    confirmed: '已确认',
    completed: '已完成',
    cancelled: '已取消',
    accepted: '待服务',
    inProgress: '服务中'
  }
  return texts[status] || status
}

// 服务记录对话框相关
const recordDialogVisible = ref(false)
const recordForm = reactive({
  content: '',
  location: ''
})
const recordRules = {
  content: [
    { required: true, message: '请输入服务内容', trigger: 'blur' }
  ]
}
const recordFormRef = ref(null)

const handleAddRecord = (order) => {
  recordDialogVisible.value = true
}

const submitRecord = async () => {
  try {
    await recordFormRef.value.validate()
    // 这里可以添加提交服务记录的逻辑
    recordDialogVisible.value = false
    ElMessage.success('服务记录添加成功')
  } catch (error) {
    ElMessage.error('请填写完整服务记录')
  }
}

// 图片预览相关
const previewVisible = ref(false)
const previewUrl = ref('')

const handlePictureCardPreview = (file) => {
  previewUrl.value = file.url
  previewVisible.value = true
}

const handleRemove = (file, fileList) => {
  // 处理图片移除逻辑
}

const getLocation = () => {
  // 处理获取位置信息逻辑
}

const viewServiceRecord = (order) => {
  // 处理查看服务记录逻辑
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped lang="scss">
.orders-container {
  .filter-card {
    margin-bottom: 20px;
  }

  .order-list {
    .order-items {
      margin: 20px 0;

      .order-item {
        margin-bottom: 20px;

        .order-header {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .left {
            display: flex;
            align-items: center;
            gap: 10px;

            .order-no {
              font-weight: bold;
            }
          }

          .time {
            color: #909399;
            font-size: 14px;
          }
        }

        .order-content {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 20px;
          margin: 20px 0;

          h4 {
            margin: 0 0 10px;
            color: #303133;
          }

          p {
            margin: 5px 0;
            color: #606266;
          }

          .price-info {
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }

        .order-footer {
          display: flex;
          justify-content: flex-end;
          gap: 10px;
        }
      }
    }
  }
}
</style>